package de.hs_rm.mmk.group_talk.activities;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.AnimationDrawable;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.Toast;

public class Main extends Activity {
        
        private static final int VOICE_RECOGNITION_REQUEST_CODE = 1234;
        Communication comm;
        private ListView mList;
        AnimationDrawable animLogo = null;
        ArrayList<String> matches = null;
        String nickname;
        String serverhost; 
        int serverport;
        int myport;
        String serverportS;
    	String myportS;
        
    @Override  
    public void onStart() {
    	super.onStart();
    	ImageButton btnNewGroup = (ImageButton) findViewById(R.id.btn_new_group);
		ImageButton btnJoinGroup = (ImageButton) findViewById(R.id.btn_join_group);
		
    	if(!preferencesAreSet()){
			btnNewGroup.setEnabled(false);
			btnJoinGroup.setEnabled(false);
			Toast.makeText(getApplicationContext(), R.string.toast_noPreferences, Toast.LENGTH_LONG).show();
    	}else{
    		btnNewGroup.setEnabled(true);
    		btnJoinGroup.setEnabled(true);
    
    	}
    	
    	Log.d("DEBUG", "Serverhost: "+serverhost+" Serverport: "+serverport+" Myport: "+myport);
    	
    	
    }
        
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.main);
        
        // Initialize logo animation
            ImageView img = (ImageView) findViewById(R.id.logo);
            img.setImageResource(R.anim.logo);
            animLogo = (AnimationDrawable) img.getDrawable();   
            img.post(new Starter());
        
//        mList = (ListView) findViewById(R.id.list);
        ImageButton voiceControl = (ImageButton)findViewById(R.id.btn_startVoiceControl);
        PackageManager pm = getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(
                new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
        
        ConnectivityManager conMgr =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
            if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED && activities.size() != 0
                        || conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTED && activities.size() != 0) {
                Log.d("TAG", "Internet");
                voiceControl.setEnabled(true);
            }else{
                Log.d("TAG", "Kein Internet");
                voiceControl.setEnabled(false);
            }
    }
    
    public boolean onCreateOptionsMenu(Menu menu){
                getMenuInflater().inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }
    
    public boolean preferencesAreSet(){
    	final SharedPreferences preferences = Preferences.getPreferences(this);
        nickname = preferences.getString("nickname", "").trim(); 
        serverhost = preferences.getString("serverhost", "").trim();
        if(serverhost.length() > 0){
        	try {
            	InetAddress iadress = InetAddress.getByName(serverhost);
    	        serverhost = iadress.getHostAddress();
    		} catch (UnknownHostException e) {
    			// TODO Auto-generated catch block
    			e.printStackTrace();
    		}
        }
        
		serverportS = preferences.getString("serverport", "").trim();
        if(serverportS.length() == 0){
        	serverport = 0;
        }else{
        	serverport = Integer.valueOf(preferences.getString("serverport", ""));
        }
        
        myportS = preferences.getString("serverport", "").trim();
        if(myportS.length() == 0){
        	myport = 0;
        }else{
        	myport = Integer.valueOf(preferences.getString("myport", ""));
        }
        
    	if(nickname.length() == 0 || serverhost.length() == 0 || serverport == 0 || myport == 0){
    		return false;
    	}else{
    		return true;
    	}	
    }
    
    public boolean onOptionsItemSelected(MenuItem item){
        switch(item.getItemId()){
                case R.id.menu_preferences:
                        startActivity(new Intent(getApplicationContext(), Preferences.class));
                        return true;
                case R.id.menu_about:
                        openAbout();
                        return true;
                case R.id.menu_exit:
                        finish();
                        return true;
                default:
                        return super.onOptionsItemSelected(item);
        }
    }
    
    public void openAbout(){
        
    }

    public void openCreateGroupActivity(final View view){
        startActivity(new Intent(getApplicationContext(), CreateGroup.class));
    }
    
    public void openShowGroupsList(final View view){
        comm = Communication.getInstance(serverhost, new Integer(myport).intValue(), new Integer(serverport).intValue());		
        
        Log.d("DEBUG", "Serverhost: "+serverhost+" Serverport: "+serverport+" Myport: "+myport);
        Log.d("DEBUG", ""+comm);
        final CharSequence[] items = comm.getAllGroups();
           
        if(items == null)
        	Toast.makeText(this.getApplicationContext(), "NO GROUPS AVAILABLE", Toast.LENGTH_LONG).show();
        
        else {
        	
	        AlertDialog.Builder builder = new AlertDialog.Builder(this);
	        builder.setTitle(R.string.alert_groupListTitle);
	        builder.setItems(items, new DialogInterface.OnClickListener() {
	                public void onClick(DialogInterface dialog, int item) {	               
		                	
		                String response = comm.canNewMemberJoinGroup((String)items[item], nickname);
		                
		                if(response.equals("OK")) {
		                	
		                	comm.updateMemberListViewNewMember((String)items[item], nickname);
		                	
			                Intent intent = new Intent(getApplicationContext(),  UserView.class);
			                        intent.putExtra("Groupname", items[item]);
			                startActivity(intent);
			            }
		                
		               
		                else
		                	Toast.makeText(getApplicationContext(), "JOIN GROUP FAILED", Toast.LENGTH_LONG).show();
		                
		                
		                }
	        });
	        AlertDialog alert = builder.create();
	        alert.show();
        }
    }
    
    public void startVoiceControl(final View view){
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 2);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Group Talk Speech Recognition");
        startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) { 
            matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
//            mList.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
//                    matches));
        }
        
        for(int i = 0; i<matches.size(); i++){
                if(matches.get(i).contentEquals("create group")){
                        startActivity(new Intent(getApplicationContext(), CreateGroup.class));
                        break;
                }else if(matches.get(i).contentEquals("join group")){
                        Toast.makeText(getApplicationContext(), "JOIN GROUP", Toast.LENGTH_SHORT).show();
                        break;
                }else{
                        Toast.makeText(getApplicationContext(), "No exact match. Please try again.", Toast.LENGTH_SHORT).show();
                }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }
    
    class Starter implements Runnable {
                public void run() {
                        animLogo.start();
                }
        }
}
